package org.kolonitsky.translator;

import org.kolonitsky.translator.filter.Filter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author Alex.Kolonitsky
 */

public class TranslatorChain extends BaseTranslator {

    protected static final Log LOG = LogFactory.getLog(TranslatorChain.class);

    private final Translator translators[];
    private final Filter filter;

    public TranslatorChain(Filter filter, Translator... translators) {
        super(getToLang(translators));
        this.filter = filter;
        this.translators = translators;
    }

    public TranslatorChain(Translator... translators) {
        this(null, translators);
    }

    protected static Lang getToLang(Translator[] translators) {
        Lang lang = null;
        for (Translator translator : translators) {
            if (lang == null) {
                lang = translator.to();
            } else if (lang != translator.to()) {
                throw new IllegalStateException("All translators in TranslatorChain should have same from/to languages");
            }
        }

        return lang;
    }

    public String translate(String text) {
        assert text != null && text.length() > 0;

        if (filter != null && !filter.shouldTranslate(text)) {
            return text;
        }

        for (Translator translator : translators) {
            String translation = translator.translate(text);
            if (translation != null && translation.length() > 0) {
                LOG.info("translate - " + translator.getClass().getSimpleName() + " - '" + text + "'");
                return translation;
            }
        }

        LOG.debug("We have not found translation for '" + text + "'");
        return new FakeTranslator(to).translate(text);
    }
}
